var vm = new Vue({
  el:'#sign',
  mixins: [mixin],
  data:{
    loading:false,
    siteTaskUnitId:'', // 企业签到记录id， 由项目详情中主题单位签名列表中获取
    familysignatureurl:"",
    basedata: "",
    ctx: null,
    point: {
      x: 0,
      y: 0,
    },
    lineColor:"#000000", // 线条颜色，默认黑色
    lineWidth:5, // 线条宽度
    moving: false, // 是否正在绘制中且移动
  },
  created: function () {
    this.siteTaskUnitId =  this.getQueryString('siteTaskUnitId');
  },
  mounted:function () {
    var board = this.$refs.board; // 获取DOM
    board.width = this.$refs.boardBox.offsetWidth; // 设置画布宽
    board.height = this.$refs.boardBox.offsetHeight; // 设置画布高
    this.ctx = board.getContext("2d"); // 二维绘图
    this.ctx.strokeStyle = this.lineColor; // 颜色
    this.ctx.lineWidth = this.lineWidth; // 线条宽度
  },
  methods: {
    // 切换线条颜色
    changeLineColor:function (val) {
      this.lineColor = val;
      this.ctx.strokeStyle = this.lineColor; // 颜色
    },
    // 触摸(开始)
    mStart(e) {
      var x = e.touches[0].clientX - e.target.offsetLeft,
        y = e.touches[0].clientY - e.target.offsetTop; // 获取触摸点在画板（canvas）的坐标
      this.point.x = x;
      this.point.y = y;
      this.ctx.beginPath();
      this.moving = true;
    },
    // 滑动中...
    mMove(e) {
      if (this.moving) {
        var x = e.touches[0].clientX - e.target.offsetLeft,
          y = e.touches[0].clientY - e.target.offsetTop; // 获取触摸点在画板（canvas）的坐标
        this.ctx.moveTo(this.point.x, this.point.y); // 把路径移动到画布中的指定点，不创建线条(起始点)
        this.ctx.lineTo(x, y); // 添加一个新点，然后创建从该点到画布中最后指定点的线条，不创建线条
        this.ctx.stroke(); // 绘制
        (this.point.x = x), (this.point.y = y); // 重置点坐标为上一个坐标
      }
    },
    // 滑动结束
    mEnd() {
      if (this.moving) {
        this.ctx.closePath(); // 停止绘制
        this.moving = false; // 关闭绘制开关
      }
    },
    getcanvas() {
      var vm = this;
      //绘画转图片
      //document.getElementById("canvas").toDataURL("image/png");
    /*  document.getElementById("canvas").toBlob(async (blobObj) => {
        var file = new File([blobObj], "pic.png", {
          type: blobObj.type,
          lastModified: Date.now(),
        });
        var oReader = new FileReader();
        oReader.readAsDataURL(file);
        oReader.onload = function (e) {
          var img = new Image();
          img.src = e.target.result;
          img.onload = function () {
            var imageData = vm.ctx.getImageData(0,0,vm.$refs.boardBox.offsetWidth,vm.$refs.boardBox.offsetHeight).data;
            // 处理空白没像素的部分
            var lOffset = vm.$refs.boardBox.offsetWidth,
                rOffset = 0,
                tOffset = vm.$refs.boardBox.offsetHeight,
                bOffset = 0;
            for (var i = 0; i < vm.$refs.boardBox.offsetWidth; i++) {
              for (var j = 0; j < vm.$refs.boardBox.offsetHeight; j++) {
                var pos = (i + vm.$refs.boardBox.offsetWidth * j) * 4
                if (imageData[pos] == 255 || imageData[pos + 1] == 255 || imageData[pos + 2] == 255 || imageData[pos + 3] == 255) {
                  bOffset = Math.max(j, bOffset); // 找到有色彩的最下端
                  rOffset = Math.max(i, rOffset); // 找到有色彩的最右端
                  tOffset = Math.min(j, tOffset); // 找到有色彩的最上端
                  lOffset = Math.min(i, lOffset); // 找到有色彩的最左端
                }
              }
            }
            lOffset++;
            rOffset++;
            tOffset++;
            bOffset++;

            var x = document.createElement("canvas"); //创建处理后画布对象
            x.width = rOffset - lOffset;
            x.height = bOffset - tOffset;
            var xx = x.getContext("2d");
            xx.drawImage(img, lOffset, tOffset, x.width, x.height, 0, 0, x.width, x.height); //绘制

            console.log(x.toDataURL()); //得到最终裁剪出来的base64

            var imgdiv = document.createElement('img');
            imgdiv.src = x.toDataURL();
            document.body.appendChild(imgdiv);
          };
        };
      });*/
    },
    //旋转图片
    convertImg(file) {
      var _this = this;
      var canvas1 = document.createElement("canvas");
      var context1 = canvas1.getContext("2d");
      var oReader = new FileReader();
      oReader.readAsDataURL(file);
      oReader.onload = function (e) {
        var img = new Image();
        img.src = e.target.result;
        img.onload = function () {
          // 图片原始尺寸
          var originWidth = this.width;
          var originHeight = this.height;
          // 最大尺寸限制
          var maxWidth = 1080,
            maxHeight = 1080;
          // 目标尺寸
          var targetWidth = originWidth,
            targetHeight = originHeight;
          // 图片尺寸超过300x300的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              targetWidth = maxWidth;
              targetHeight = Math.round(
                maxWidth * (originHeight / originWidth)
              );
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(
                maxHeight * (originWidth / originHeight)
              );
            }
          }
          var type = "image/jpeg";
          // canvas对图片进行缩放
          canvas1.width = targetHeight;
          canvas1.height = targetWidth;
          // 旋转90度
          context1.translate(0, 0);
          context1.rotate(90*Math.PI / 180);
          // (0,-imgHeight) 从旋转原理图那里获得的起始点
          // context.clearRect(0,  -targetHeight, targetWidth, targetHeight);
          context1.drawImage(img, 0, -targetHeight, targetWidth, targetHeight);
          // 将canvas的透明背景设置成白色
          var imageData = context1.getImageData(
            0,
            0,
            canvas1.width,
            canvas1.height
          );
          for (var i = 0; i < imageData.data.length; i += 4) {
            // 当该像素是透明的，则设置成白色
            if (imageData.data[i + 3] == 0) {
              imageData.data[i] = 245;
              imageData.data[i + 1] = 245;
              imageData.data[i + 2] = 245;
              imageData.data[i + 3] = 245;
            }
          }
          context1.putImageData(imageData, 0, 0);
          var dataurl = canvas1.toDataURL(type);
          _this.basedata = dataurl;
          console.log(dataurl);
          _this.postUnitSign();
          //_this.updatavue();
        };
      };
    },
    //base64转Blob
    base64ToBlob(base64Data) {
      var arr = base64Data.split(","),
        fileType = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        l = bstr.length,
        u8Arr = new Uint8Array(l);

      while (l--) {
        u8Arr[l] = bstr.charCodeAt(l);
      }
      return new Blob([u8Arr], {
        type: fileType,
      });
    },
    //上传图片
    async updatavue() {
      //转成file文件
      var blobObj = this.base64ToBlob(this.basedata);
      var file = new File([blobObj], "pic.png", {
        type: blobObj.type,
        lastModified: Date.now(),
      });
      //此处为发送请求给后台获取图片路径
      var res = await upload(file);
      this.familysignatureurl=res.details.data.filePath
      console.log(this.familysignatureurl);//此处打印的为绘画的图片url
    },
    //清除画布
    clearcanvas() {
      var c = document.getElementById("canvas");
      var cxt = c.getContext("2d");
      c.height = c.height;
      this.ctx.lineWidth = this.lineWidth;
    },
    //返回上一级
    goback() {
      this.$emit("setshow");
    },
    //  签到接口
    postUnitSign:function () {
      var vm = this;
     // vm.loading = true;
      var params =JSON.stringify({
        siteTaskUnitId:vm.siteTaskUnitId, // 企业签到记录id， 由项目详情中主题单位签名列表中获取
        signBase64:vm.basedata.substring(vm.basedata.indexOf(",")+1), // 去掉 “data:image/jpeg;base64,”
      })
      // $.ajax({
      //   url: ctx + 'rest/site/task/unit/sign',
      //   type: 'post',
      //   contentType:"application/json",
      //   data:params,
      //   success: function (res) {
      //     vm.loading = false;
      //     if (res.success) {
      //       vm._alertState(true, '签名成功');
      //       setTimeout(function () {
      //         sessionStorage.setItem("refresh","true");
      //         window.history.go(-2);
      //       },1000)
      //     } else {
      //       vm._alertState(true, res.message);
      //     }
      //   },
      //   error: function (err) {
      //     vm.loading = false;
      //     vm._alertState(true, '服务器接口请求失败！')
      //   },
      // })
    },
    getQueryString:function (name) {
      return getQueryString(name);
    }
  }
})